package com.sky.com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BusinessException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatProperties weChatProperties;

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";


    @Override
    public User login(UserLoginDTO userLoginDTO) {
      //1.参数校验
        if(StrUtil.isBlank(userLoginDTO.getCode())){
            throw new BusinessException(200,"code不能为空");
        }
        //2. 微信登录 (向微信要一个openid)
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("grant_type","");
        paramMap.put("js_code",userLoginDTO.getCode());
        //发送请求
        String json = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        //json转Map
        Map<String,String> map = JSON.parseObject(json, Map.class);
        //校验是否有openid
        String openid = map.get("openid");
        if(StrUtil.isBlank(openid)){
            throw new BusinessException(200,"微信登录失败");
        }
        //3. 判断是否为新用户
        User user = userMapper.getByOpenid(openid);
        if(user == null){
            //注册
            user=new User();
            user.setOpenid(openid);
            userMapper.insert(user); //开启主键返回
        }
        //4. 返回user
        return user;
    }


    /**
     * 调用微信登陆凭证校验接口，获取openid
     * **/
    private String getOpenid(UserLoginDTO userLoginDTO) {
        HashMap<String, String> params = new HashMap<>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code", userLoginDTO.getCode());
        params.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, params);
        String openid = (String) JSONUtil.parseObj(json).get("openid");
        if(StrUtil.isBlank(openid)){
            throw new BusinessException(500,"登录异常,请重试");
        }
        return openid;
    }
}
